﻿<?php

/**
 * Payment actions.
 *
 * @package    5
 * @subpackage Payment
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class PaymentActions extends sfActions
{
  public function preExecute()
  {
    $request = $this->getRequest();
    $expIds = $request->getParameter('explanation_ids');
    $testId = $request->getParameter('test_id');

    if (!count($expIds)) {
      $this->setTemplate('empty');
      return ;
    }

    if (!$testId) {
      $this->setTemplate('error');
      return ;
    }

    $this->test = Doctrine_Core::getTable('Test')->findOneByIdAndUserId($testId, $this->getUser()->getId());
    if (!$this->test) {
      $this->setTemplate('error');
      return ;
    }

    $this->explanations = Doctrine_Core::getTable('Explanation')->createQuery('e')
      ->whereIn('e.id', $expIds)
      ->execute();

    if (!count($this->explanations)) {
      $this->setTemplate('error');
      return ;
    }
  }

  public function executeConfirm(sfWebRequest $request)
  {
  }

  public function executePay(sfWebRequest $request)
  {
    // $money is real money
    $money = $money2 = $this->getUser()->getPoint();
    foreach ($this->explanations as $explanation) {
      $money2 -= $explanation->getCost();
      if ($money2 >= 0) { 
        $log = new PaymentLog();
        $log->setExplanationId($explanation->getId())
          ->setTestId($this->test->getId())
          ->setCost($explanation->getCost())
          ->save();
        $money = $money2;
      } else {
        break;
      }
    }
    if ($money != $this->getUser()->getPoint()) {
      // if the money is changed
      $this->getUser()->setMoney($money)->save();
    }
  }
}
